<?php
// 仅当会话尚未启动时调用 session_start()
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户角色，确保只有管理员可以操作
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header('Location: http://localhost/Library_management_system/index.php');
    exit();
}

// 连接数据库
$pdo = new PDO('mysql:host=localhost;dbname=library', 'root', '123456');

// 处理插入新图书
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['insert'])) {
    $book_No = $_POST['book_No'];
    $P_ID = $_POST['P_ID'];
    $B_name = $_POST['B_name'];
    

    $ISBN = $_POST['ISBN'];

    // 插入新图书时设置 Loan_Id 为 NULL，推荐度为 0
    $stmt = $pdo->prepare('
        INSERT INTO book (book_No, P_ID, Loan_Id, B_name,   Recommendation_degree, ISBN)
        VALUES (?, ?, NULL,  ?,  0, ?)
    ');

    $stmt->execute([$book_No, $P_ID, $B_name, $ISBN]);

    echo "新图书已插入！";
}

// 处理删除图书
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete'])) {
    $search_value = $_POST['search_value'];
    
    // 根据图书编号（book_No）或图书名称（name）删除图书
    $stmt = $pdo->prepare('
        DELETE FROM book WHERE book_No = ? OR B_name = ?
    ');

    $stmt->execute([$search_value, $search_value]);

    echo "图书已删除！";
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理图书</title>
</head>
<body>
    <h2>管理图书</h2>

    <!-- 插入新图书表单 -->
    <h3>插入新图书</h3>
    <form method="POST">
        <label for="book_No">图书编号:</label>
        <input type="text" name="book_No" required><br>

        <label for="P_ID">出版社ID:</label>
        <input type="text" name="P_ID" required><br>

        <label for="B_name">图书名称:</label>
        <input type="text" name="B_name" required><br>

      

        <label for="ISBN">ISBN:</label>
        <input type="text" name="ISBN" required><br>

        <button type="submit" name="insert">插入新图书</button>
    </form>

    <hr>

    <!-- 删除图书表单 -->
    <h3>删除图书</h3>
    <form method="POST">
        <label for="search_value">输入图书编号或名称:</label>
        <input type="text" name="search_value" required><br>

        <button type="submit" name="delete">删除图书</button>
    </form>
</body>
</html>
